<?php

namespace App\Http\Controllers\Freelancer;

use App\Http\Controllers\Controller;
use App\Models\SubSettlement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class SettlementController extends Controller
{
    /**
     * 获取自由职业者的结算记录列表
     */
    public function index(Request $request)
    {
        $statusOptions = array_keys(SubSettlement::STATUS_LABELS);

        $validator = Validator::make($request->all(), [
            'page' => 'integer|min:1',
            'per_page' => 'integer|min:1|max:100',
            'status' => ['string', Rule::in($statusOptions)],
            'start_date' => 'date',
            'end_date' => 'date|after_or_equal:start_date',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 1,
                'message' => '参数验证失败',
                'data' => $validator->errors()
            ]);
        }

        try {
            $freelancer = $request->user();
            $perPage = $request->get('per_page', 20);

            $query = SubSettlement::where('freelancer_id', $freelancer->id)
                ->orderBy('created_at', 'desc');

            // 状态筛选
            if ($request->filled('status')) {
                $query->where('status', $request->status);
            }

            // 时间范围筛选
            if ($request->filled('start_date')) {
                $query->whereDate('created_at', '>=', $request->start_date);
            }
            if ($request->filled('end_date')) {
                $query->whereDate('created_at', '<=', $request->end_date);
            }

            $settlements = $query->paginate($perPage);

            // 格式化数据
            $formattedData = $settlements->getCollection()->map(function ($settlement) {
                return [
                    'id' => $settlement->id,
                    'sub_settlement_number' => $settlement->sub_settlement_number,
                    'settlement_id' => $settlement->settlement_id,
                    'pre_settlement_amount' => $settlement->pre_settlement_amount,
                    'commission' => $settlement->commission,
                    'service_fee' => $settlement->service_fee,
                    'service_fee_rate' => $settlement->service_fee_rate,
                    'tax' => $settlement->tax,
                    'required_balance' => $settlement->required_balance,
                    'status' => $settlement->status,
                    'status_display' => $settlement->status_display,
                    'status_description' => $settlement->status_description,
                    'payment_remarks' => $settlement->payment_remarks,
                    'electronic_receipt' => $settlement->electronic_receipt,
                    'created_at' => $settlement->created_at ? $settlement->created_at->format('Y-m-d H:i:s') : null,
                    'verified_at' => $settlement->verified_at ? $settlement->verified_at->format('Y-m-d H:i:s') : null,
                    'submitted_at' => $settlement->submitted_at ? $settlement->submitted_at->format('Y-m-d H:i:s') : null,
                    'distributed_at' => $settlement->distributed_at ? $settlement->distributed_at->format('Y-m-d H:i:s') : null,
                    'cancelled_at' => $settlement->cancelled_at ? $settlement->cancelled_at->format('Y-m-d H:i:s') : null,
                ];
            });

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => [
                    'settlements' => $formattedData,
                    'pagination' => [
                        'current_page' => $settlements->currentPage(),
                        'per_page' => $settlements->perPage(),
                        'total' => $settlements->total(),
                        'last_page' => $settlements->lastPage(),
                        'from' => $settlements->firstItem(),
                        'to' => $settlements->lastItem(),
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '获取结算记录失败',
                'data' => null
            ]);
        }
    }

    /**
     * 获取结算记录详情
     */
    public function show(Request $request, $id)
    {
        try {
            $freelancer = $request->user();

            $settlement = SubSettlement::where('freelancer_id', $freelancer->id)
                ->where('id', $id)
                ->first();

            if (!$settlement) {
                return response()->json([
                    'code' => 1,
                    'message' => '结算记录不存在',
                    'data' => null
                ]);
            }

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => [
                    'id' => $settlement->id,
                    'sub_settlement_number' => $settlement->sub_settlement_number,
                    'settlement_id' => $settlement->settlement_id,
                    'freelancer_name' => $settlement->freelancer_name,
                    'freelancer_phone' => $settlement->freelancer_phone,
                    'freelancer_id_card' => $settlement->freelancer_id_card,
                    'freelancer_bank_account' => $settlement->freelancer_bank_account,
                    'freelancer_bank_name' => $settlement->freelancer_bank_name,
                    'pre_settlement_amount' => $settlement->pre_settlement_amount,
                    'commission' => $settlement->commission,
                    'service_fee' => $settlement->service_fee,
                    'service_fee_rate' => $settlement->service_fee_rate,
                    'tax' => $settlement->tax,
                    'required_balance' => $settlement->required_balance,
                    'status' => $settlement->status,
                    'status_display' => $settlement->status_display,
                    'status_description' => $settlement->status_description,
                    'payment_remarks' => $settlement->payment_remarks,
                    'electronic_receipt' => $settlement->electronic_receipt,
                    'created_at' => $settlement->created_at ? $settlement->created_at->format('Y-m-d H:i:s') : null,
                    'verified_at' => $settlement->verified_at ? $settlement->verified_at->format('Y-m-d H:i:s') : null,
                    'submitted_at' => $settlement->submitted_at ? $settlement->submitted_at->format('Y-m-d H:i:s') : null,
                    'distribute_started_at' => $settlement->distribute_started_at ? $settlement->distribute_started_at->format('Y-m-d H:i:s') : null,
                    'distributed_at' => $settlement->distributed_at ? $settlement->distributed_at->format('Y-m-d H:i:s') : null,
                    'cancelled_at' => $settlement->cancelled_at ? $settlement->cancelled_at->format('Y-m-d H:i:s') : null,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '获取结算记录详情失败',
                'data' => null
            ]);
        }
    }

    /**
     * 获取结算统计信息
     */
    public function statistics(Request $request)
    {
        try {
            $freelancer = $request->user();

            $stats = [
                'total_count' => SubSettlement::where('freelancer_id', $freelancer->id)->count(),
                'completed_count' => SubSettlement::where('freelancer_id', $freelancer->id)
                    ->where('status', SubSettlement::STATUS_COMPLETED)->count(),
                'pending_count' => SubSettlement::where('freelancer_id', $freelancer->id)
                    ->whereIn('status', [
                        SubSettlement::STATUS_VERIFYING,
                        SubSettlement::STATUS_PENDING_TAX,
                        SubSettlement::STATUS_PENDING_SUBMIT,
                        SubSettlement::STATUS_PENDING_DISTRIBUTE,
                        SubSettlement::STATUS_DISTRIBUTING
                    ])->count(),
                'total_commission' => SubSettlement::where('freelancer_id', $freelancer->id)
                    ->where('status', SubSettlement::STATUS_COMPLETED)
                    ->sum('commission'),
                'this_month_commission' => SubSettlement::where('freelancer_id', $freelancer->id)
                    ->where('status', SubSettlement::STATUS_COMPLETED)
                    ->whereMonth('distributed_at', now()->month)
                    ->whereYear('distributed_at', now()->year)
                    ->sum('commission'),
            ];

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '获取统计信息失败',
                'data' => null
            ]);
        }
    }

    /**
     * 获取状态选项
     */
    public function statusOptions()
    {
        return response()->json([
            'code' => 0,
            'message' => '获取成功',
            'data' => SubSettlement::getStatusOptions()
        ]);
    }
}
